package org.huawei.dao;

import org.huawei.model.domain.Permission;
import org.huawei.model.domain.RolePermission;
import org.huawei.utils.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RolePermissionDao {
    public List<Integer> getEnabledPermissionIdsByRoleId(int roleId) throws SQLException {
        String query = "SELECT rp.PermissionId " +
                "FROM Role_Permission rp " +
                "WHERE rp.RoleId = ? AND rp.Status = ?";

        List<Integer> permissionIds = new ArrayList<>();

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            // 设置查询参数
            stmt.setInt(1, roleId);
            stmt.setString(2, RolePermission.Status.ENABLED.name());

            // 执行查询
            ResultSet rs = stmt.executeQuery();

            // 解析结果集，存储permissionId
            while (rs.next()) {
                permissionIds.add(rs.getInt("PermissionId"));
            }
        }
        return permissionIds;
    }

    // 更新role_permission表中的状态的方法
    public void updateRolePermission(int roleId, int permissionId, boolean isEnabled) {
        try (Connection conn = DatabaseUtil.getConnection()) {
            String query = "UPDATE role_permission SET Status = ? WHERE RoleId = ? AND PermissionId = ?";
            try (PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setString(1, isEnabled ? "Enabled" : "Disabled");
                stmt.setInt(2, roleId);
                stmt.setInt(3, permissionId);
                stmt.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();  // 处理SQL异常
        }
    }

    // 从数据库加载当前状态的方法
    public boolean loadRolePermissionStatus(int roleId, int permissionId) {
        boolean isEnabled = false;
        try (Connection conn = DatabaseUtil.getConnection()) {
            String query = "SELECT Status FROM role_permission WHERE RoleId = ? AND PermissionId = ?";
            try (PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.setInt(1, roleId);
                stmt.setInt(2, permissionId);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    String status = rs.getString("Status");
                    isEnabled = "Enabled".equalsIgnoreCase(status);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();  // 处理SQL异常
        }
        return isEnabled;
    }


}
